import VectorLayer from 'ol/layer/Vector';
import VectorSource from 'ol/source/Vector';
import { Style, Fill, Stroke, Circle as CircleStyle } from 'ol/style';
import { defaultStyles } from '../config/plotStyles';
import { PlotTypes } from '../plot/PlotTypes';
import Plot from 'ol-plot';  // 确认导入路径
import 'ol-plot/dist/ol-plot.css';

class PlotService {
    constructor(map, options = {}) {
        this.map = map;
        this.source = new VectorSource();
        this.layer = new VectorLayer({
            source: this.source,
            style: (feature) => this.createStyle(feature)
        });
        this.Plot = new Plot(map, this.source);
        this.plotDraw = this.Plot.plotDraw;
        this.plotEdit = this.Plot.plotEdit;
        this.drawEndCallback = null;
        this.featureClickCallback = options.onFeatureClick; // 新增：点击回调
        this.initialize();
    }

    initialize() {
        this.map.addLayer(this.layer);
        this.map.on("click", (event) => {
            const feature = this.map.forEachFeatureAtPixel(
                event.pixel,
                function (feature) {
                    return feature;
                }
            );
            if (feature && feature.get("isPlot") && !this.plotDraw.isDrawing()) {
                this.plotEdit.activate(feature);
                // 新增：调用回调函数
                if (this.featureClickCallback) {
                    const style = this.Plot.plotUtils.getBaseStyle(feature);
                    this.featureClickCallback({
                        feature,
                        style,
                        isPlot: true
                    });
                }
            } else {
                this.plotEdit.deactivate();
                // 新增：调用回调函数
                if (this.featureClickCallback) {
                    this.featureClickCallback({
                        feature: null,
                        style: null,
                        isPlot: false
                    });
                }
            }
        });
        this.Plot.on("activeTextArea", (e) => {
            console.log("文本框已激活编辑:", e);
            let lastClickTime = 0; // 添加时间戳变量

            // 在这里可以添加额外的逻辑，如显示编辑工具栏等
            let feature = e.overlay;
            let style = e.overlay.getStyle();
            console.log(style);
            style.fontSize = parseInt(style.fontSize.replace("px", ""));
            style.lineHeight =
              style.lineHeight == "normal"
                ? 10
                : parseFloat(style.lineHeight.replace("px", ""));
            style.fontFamily =
              style.fontFamily ==
                '"Helvetica Neue", Helvetica, "PingFang SC", "Hiragino Sans GB", "Microsoft YaHei", "Noto Sans CJK SC", "WenQuanYi Micro Hei"' ||
              "Microsoft YaHei";
            style.fontStretch = style.fontStretch == "100%" ? "normal" : style.fontStretch;
            const currentTime = Date.now();
            if (currentTime - lastClickTime >= 3000) {
              // 检查是否过了3秒
              if (this.featureClickCallback) {
                this.featureClickCallback({
                  feature,
                  style,
                  isPlot: true,
                });
              }
              lastClickTime = currentTime; // 更新上次点击时间
            }
        });
        
    }

    createStyle(feature) {
        let geometryType;
        if (!feature) {
            geometryType = 'polygon';
        } else {
            const geometry = feature.getGeometry();
            if (geometry) {
                geometryType = geometry.getType().toLowerCase();
                const plotType = feature.get('plotType');
                if (plotType) {
                    geometryType = plotType.toLowerCase();
                }
                switch (geometryType) {
                    case 'circle':
                    case 'regularpolygon':
                        geometryType = 'polygon';
                        break;
                    case 'linearring':
                        geometryType = 'linestring';
                        break;
                }
            }
        }

        const styleConfig = defaultStyles[geometryType] || defaultStyles.polygon;
        return new Style({
            fill: styleConfig.fill ? new Fill({
                color: styleConfig.fill.color || 'rgba(0, 0, 255, 0.1)'
            }) : undefined,
            stroke: styleConfig.stroke ? new Stroke({
                color: styleConfig.stroke.color || '#0000ff',
                width: styleConfig.stroke.width || 2
            }) : undefined,
            image: styleConfig.image ? new CircleStyle({
                radius: styleConfig.image.radius || 5,
                fill: styleConfig.image.fill ? new Fill({
                    color: styleConfig.image.fill.color || '#ff0000'
                }) : undefined,
                stroke: styleConfig.image.stroke ? new Stroke({
                    color: styleConfig.image.stroke.color || '#ffffff',
                    width: styleConfig.image.stroke.width || 2
                }) : undefined
            }) : undefined
        });
    }

    activate(type, callback) {
        this.drawEndCallback = callback;
        this.deactivate();

        console.log('激活绘制类型:', type);
        this.plotDraw.activate(type);
        this.plotDraw.on('drawEnd', (event) => this.handleDrawEnd(event, type));
    }

    deactivate() {
        this.plotDraw.deactivate();
        this.plotEdit.deactivate();
        this.drawEndCallback = null;
    }

    handleDrawEnd(event, type) {
        this.plotDraw.deactivate();
        const feature = event.feature;
        feature.set('plotType', type.toLowerCase());
        this.plotEdit.activate(feature);  // 激活编辑功能
        if (this.drawEndCallback) {
            this.drawEndCallback(feature);
        }
    }

    // ...existing code for addFeature, updateFeature, removeFeature, createGeometryFromData...

    isMilitaryPlot(type) {
        if (!type) return false;
        const standardTypes = ['Point', 'LineString', 'Polygon', 'Circle', 'Rectangle', 'Hole'];
        if (standardTypes.includes(type)) {
            return false;
        }
        const lowerType = type.toLowerCase();
        const plotValues = Object.values(PlotTypes).map(val => val.toLowerCase());
        return plotValues.includes(lowerType);
    }
}

export default PlotService;